import * as React from 'react';
import classNames from 'classnames';
import { Icon } from 'antd';

export function renderSwitcherIcon(prefixCls, switcherIcon, showLine, { isLeaf, expanded, loading }) {
    if (loading) {
        return <Icon type="loading" className={`${prefixCls}-switcher-loading-icon`} />;
    }
    let showLeafIcon;
    if (showLine && typeof showLine === 'object') {
        // eslint-disable-next-line prefer-destructuring
        showLeafIcon = showLine.showLeafIcon;
    }
    if (isLeaf) {
        if (showLine) {
            if (typeof showLine === 'object' && !showLeafIcon) {
                return <span className={`${prefixCls}-switcher-leaf-line`} />;
            }
            return <Icon type="file" className={`${prefixCls}-switcher-line-icon`} />;
        }
        return null;
    }
    const switcherCls = `${prefixCls}-switcher-icon`;
    if (React.isValidElement(switcherIcon)) {
        return React.cloneElement(switcherIcon, {
            className: classNames(switcherIcon.props.className || '', switcherCls)
        });
    }

    if (switcherIcon) {
        return switcherIcon;
    }

    if (showLine) {
        return expanded ? (
            <Icon type="minus-square" className={`${prefixCls}-switcher-line-icon`} />
        ) : (
            <Icon type="plus-square" className={`${prefixCls}-switcher-line-icon`} />
        );
    }
    return <Icon type="caret-down" className={switcherCls} />;
}

export function getIcons({
    suffixIcon,
    clearIcon,
    menuItemSelectedIcon,
    removeIcon,
    loading,
    multiple,
    prefixCls
}) {
    // Clear Icon
    let mergedClearIcon = clearIcon;
    if (!clearIcon) {
        mergedClearIcon = <Icon type="close-circle" />;
    }

    // Arrow item icon
    let mergedSuffixIcon = null;
    if (suffixIcon !== undefined) {
        mergedSuffixIcon = suffixIcon;
    } else if (loading) {
        mergedSuffixIcon = <Icon type="loading" />;
    } else {
        const iconCls = `${prefixCls}-suffix`;
        mergedSuffixIcon = ({ open, showSearch }) => {
            if (open && showSearch) {
                return <Icon type="search" className={iconCls} />;
            }
            return <Icon type="down" className={iconCls} />;
        };
    }

    // Checked item icon
    let mergedItemIcon = null;
    if (menuItemSelectedIcon !== undefined) {
        mergedItemIcon = menuItemSelectedIcon;
    } else if (multiple) {
        mergedItemIcon = <Icon type="check" />;
    } else {
        mergedItemIcon = null;
    }

    let mergedRemoveIcon = null;
    if (removeIcon !== undefined) {
        mergedRemoveIcon = removeIcon;
    } else {
        mergedRemoveIcon = <Icon type="close" />;
    }

    return {
        clearIcon: mergedClearIcon,
        suffixIcon: mergedSuffixIcon,
        itemIcon: mergedItemIcon,
        removeIcon: mergedRemoveIcon
    };
}
